package youleche.com.controler.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

import youleche.com.business.BSeller;
import youleche.com.business.BVehicleImageInfo;
import youleche.com.business.BVehicleInfo;
import youleche.com.caches.CacheFactory;
import youleche.com.common.IDFactory;
import youleche.com.common.ParamConfigParameters;
import youleche.com.factory.MLLogFactory;
import youleche.com.interfaces.LoginAction;
import youleche.com.model.MVehicleImageInfo;
import youleche.com.model.MVehicleInfo;
import youleche.com.sql.servlet.common.SuperHttpServlet;
import youleche.com.util.AESEncryptAndDecrypt;
import youleche.com.util.FileUtil;
import youleche.com.util.ImageFactory;
import youleche.com.util.JsonHelper;

/**
 * Servlet implementation class SVehicleServlet
 */
public class CVehicleServlet extends SuperHttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CVehicleServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0 :	
				//发布信息
				this.release(request, response);
				break;				
			case 1 :	
				//根据ID获取车辆信息
				this.getVehicleInfoById(request, response);
				break;
			case 2 :
				//更新访问量
				this.updateCountById(request, response);
				break;
			case 3 :
				//生成联系电话图片
				this.generateImageForLinkNum(request, response);
				break;
			case 4: 
				//联系店主时获取联系方式以及部分车辆信息 
				this.getContactInfoAndVehicleInfo(request, response);
				break;
			case 5: 
				//分页
				this.page(request, response);
				break;
			case 6: 
				//删除车辆信息
				this.deleteVehicleInfoById(request, response);
				break;
			case 7: 
				//得到总条数
				this.getCount(request, response);
				break;
			case 8: 
				//首页滚动条加载车辆信息
				this.scrollGetVehicle(request, response);
				break;
			case 9 :
				//根据ID获取车辆信息
				this.getVehicleInfoByIdForNoForward(request, response);
				break;
			case 10 :
				//发布车辆报价时获取车辆信息ID
				this.getId(request, response);
				break;
		}		
	}
	
	/**
	 * 获取车辆信息ID
	 * @param request
	 * @param response
	 */
	private void getId(HttpServletRequest request, HttpServletResponse response){
		super.response(response, IDFactory.getId("mlc", "vehicleinfo"));
	}
	
	/**
	 * 首页滚动条加载车辆信息
	 * @param request
	 * @param response
	 */
	private void scrollGetVehicle(HttpServletRequest request, HttpServletResponse response){
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
		try {
			BVehicleInfo handler = new BVehicleInfo();
			List<MVehicleInfo> list = handler.getVehicleInfoList(startIndex.toString(), ((Integer)pageSize).toString());
			if(list == null || list.size() == 0){
				super.response(response, "");
				return;
			}
			
			JsonHelper.printListToJsonString(response, list);
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "");
		}
	}
	
	/**
	 * 得到总条数
	 * @param request
	 * @param response
	 */
	private void getCount(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		try {
			super.response(response, handler.getCount());
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, 0);
		}
	}
	
	/**
	 * 删除车辆信息
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings("static-access")
	private void deleteVehicleInfoById(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		try {
			String vehicleId = request.getParameter("id");
			if(handler.deleteVehicleInfoById(vehicleId) > 0 ){
				BVehicleImageInfo imgHandler = new BVehicleImageInfo();
				List<MVehicleImageInfo> imgInfoList = imgHandler.getImageInfoByVehicleId(vehicleId);
				if(imgInfoList != null && imgInfoList.size() > 0){
					for (MVehicleImageInfo img : imgInfoList) {
						FileUtil.deleteFile(img.getImagePath(), request.getSession().getServletContext().getRealPath("/") + "vehicleImage/");
					}
				}
				CacheFactory.getVehicleCache().updateCache();
				super.response(response, 1);
			}else{
				super.response(response, 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, 0);
		}
	}
	
	/**
	 * 分页
	 * @param request 请求
	 * @param response 响应
	 */
	private void page(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		try {
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));
			Integer startIndex = (Integer.parseInt(request.getParameter("pageIndex")) - 1) * pageSize ;
			List<MVehicleInfo> list = handler.getVehicleInfoList(startIndex.toString(), ((Integer)pageSize).toString());
			JsonHelper.printListToJsonString(response, list);	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取联系时的信息
	 * @param request 请求
	 * @param response 响应
	 */
	private void getContactInfoAndVehicleInfo(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		BVehicleImageInfo handlerImage = new BVehicleImageInfo();
		try {
			request.setAttribute("vehicleContact", handler.getVehicleInfoById(request.getParameter("id")));
			request.setAttribute("vehicleImageContact", handlerImage.getImageInfoByVehicleId(request.getParameter("id")));
			request.getRequestDispatcher("/contact.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成联系电话图片
	 * @param request 请求
	 * @param response 响应
	 */
	private void generateImageForLinkNum(HttpServletRequest request, HttpServletResponse response){
		try {
			String callNum = request.getParameter("callNum");
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String key = paramConfig.getParameter("LinkNum_KEY");
			ImageFactory.generateCellPhoneNumber(response.getOutputStream(), AESEncryptAndDecrypt.decrypt(callNum, key));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 更新访问量
	 * @param request 请求
	 * @param response 响应
	 */
	private void updateCountById(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		try {
			String vehicleId = request.getParameter("id");
			Integer count = handler.getCountById(vehicleId) + 1;
			handler.updateCountById(vehicleId, count.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发布信息
	 * @param request 请求
	 * @param response 响应
	 */
	@SuppressWarnings("static-access")
	private void release(HttpServletRequest request, HttpServletResponse response){
		try {
			
			LoginAction actionHandler = new LoginAction();
			if(actionHandler.isLoginToInner(request, response) == "true"){
				MVehicleInfo vehicleInfo = (MVehicleInfo) JsonHelper.getObjectByJsonStringAndDateFormat(request, MVehicleInfo.class, "yyyy-MM-dd");
				BVehicleInfo handler = new BVehicleInfo();
				ParamConfigParameters paramConfig = new ParamConfigParameters();
				String key = paramConfig.getParameter("LinkNum_KEY");
				vehicleInfo.setLinkPhoneNum(AESEncryptAndDecrypt.encrypt(vehicleInfo.getLinkPhoneNum(), key));
				///今天该用户发布的条数
				String todayCount = handler.getVehicleInfoCountForTodayBySellerId(vehicleInfo.getSellerId());
				if(todayCount == null || "".equals(todayCount)){
					todayCount = "0";
				}
				
				int todayCountInt = Integer.parseInt(todayCount);
				if(todayCountInt > 3){
					super.response(response, "2"); //用户今天已经发布超过3条信息了
					return;
				}
				
				if(handler.addVehicleInfo(vehicleInfo) > 0){
					CacheFactory.getVehicleCache().updateCache();
					///更新信用指数
					BSeller sellerHandler = new BSeller();
					String creditIndexStr = sellerHandler.getSellerCreditById(vehicleInfo.getSellerId());
					double creditIndex = Double.parseDouble(creditIndexStr);
					sellerHandler.updateSellerCreditById(vehicleInfo.getSellerId(), ((Double)(creditIndex + 0.1)).toString());
					super.response(response, "1");
				}
			}else{
				super.response(response, "0");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "0");
			MLLogFactory.exceptionLog("用户发布报价信息出错", "用户发布报价信息出错", e.getMessage(), request.getRemoteAddr());
		}
	}
	
	/**
	 * 根据ID获取车辆信息
	 * @param request
	 * @param response
	 */
	private void getVehicleInfoByIdForNoForward(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		
		try {
			MVehicleInfo info = handler.getVehicleInfoById(request.getParameter("id"));
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String key = paramConfig.getParameter("LinkNum_KEY");
			info.setLinkPhoneNum(AESEncryptAndDecrypt.decrypt(info.getLinkPhoneNum(), key));
			Gson gson = new Gson();
			super.response(response, gson.toJson(info));
		} catch (Exception e) {
			super.response(response, "");
			MLLogFactory.exceptionLog("根据ID获取车辆信息发生异常", "根据ID获取车辆信息发生异常", e.getMessage(), request.getRemoteAddr());
		}
	}
	
	/**
	 * 根据ID获取车辆信息
	 * @param request 请求
	 * @param response 响应
	 */
	private void getVehicleInfoById(HttpServletRequest request, HttpServletResponse response){
		BVehicleInfo handler = new BVehicleInfo();
		
		try {
			request.setAttribute("vehicle", handler.getVehicleInfoById(request.getParameter("id")));
			request.getRequestDispatcher("/detail.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
